# -*- coding: utf-8 -*-
import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from pylons.decorators import validate
from formencode import htmlfill
from formencode import validators
import formencode
from pythonblog.lib.base import BaseController, render
import pythonblog.lib.helpers as h
from pythonblog.model.account import *
from pythonblog.service import user_service
from pythonblog.service import content_service
from pythonblog.controllers import custom_formatter
from pythonblog.controllers import UserProfileUpdateForm

log = logging.getLogger(__name__)

class BlogController(BaseController):
    
    def __before__(self):
        sub_domain = self.get_sub_domain(request.environ)
        userInfo = user_service.get_user(sub_domain)
        if not userInfo:
            abort(404)
                 
        c.userInfo = userInfo
        c.blogInfo = content_service.get_blog_info(userInfo.id)
        #c.posts = content_service.get_posts(userProfile.id)

    def profile_view(self):    
        return render('/derived/blog/profile_view.html')
    
    def profile_edit(self):
        self.validate(c.userInfo.userName, request.environ)
        return htmlfill.render(render('/derived/blog/profile_edit.html'), defaults = c.userInfo.__dict__)
    """
    @validate(schema=UserProfileUpdateForm(state={"userName": c.userInfo.userName}), form='profile_edit', post_only=False,
              on_get=True, auto_error_formatter=custom_formatter)"""
    def profile_update(self):
        self.validate(c.userInfo.userName, request.environ)
        schema = UserProfileUpdateForm()
        try:
            c.form_result = schema.to_python(dict(request.params), state=c.userInfo)
        except formencode.Invalid, error:
            c.form_result = error.value
            c.form_errors = error.error_dict or {}
            html = render('/derived/blog/profile_edit.html')
            return formencode.htmlfill.render(
                html,
                defaults=c.form_result,
                errors=c.form_errors,
                auto_error_formatter=custom_formatter
                )
        else:
            user = user_service.get_user_from_db(c.userInfo.id)
            if not user:
                abort(404)
            user.realName = c.form_result['realName']
            user.gender = c.form_result['gender']
            email = c.form_result['email']
            if not email:
                user.email = None
            else:
                user.email = email
            user.city = c.form_result['city']
            user.vocation = c.form_result['vocation']
            user.industry = c.form_result['industry']
            meta.Session.add(user)

            if c.form_result['password']:
                users = request.environ['authkit.users']
                users.user_set_password(c.userInfo.userName, c.form_result['password'])

            meta.Session.commit()
            user_service.add_or_update_to_cache(user)
            redirect_to(controller='blog', action='profile_view', sub_domain=c.userInfo.userName)
        
